<?php
class LESSPHP_Plugin_BasicCss extends LESSPHP_Plugin_Abstract{
	
	public function apply(SimpleXMLElement $cssXml){
		
	}
	
	protected function _parseSelectors($rawSelectors){
		$rawSelectors = trim($rawSelectors);
		$rawSelectors = explode(',', $rawSelectors);
		$rawSelectors = array_map('trim', $rawSelectors);
		
		$output = '';
		foreach($rawSelectors as $selector){
			$output .= '<selector>' . $selector . '</selector>';
		}
		return $output;
	}
	
	public function transformCss($css){
		$css = $this->_transformComments($css);
		$css = $this->_transformProperties($css);
		$css = $this->_transformSelectors($css);
		
		//([a-zA-Z0-9,\s:.#_-]+)\s?{                         properties
		return $css;
	}
	
	protected function _transformComments($css){
		$css = preg_replace('%/\\*\s*(.*?)\s*\\*/%s', '<comment><![CDATA[$1]]></comment>', $css);
		return $css;
	}
	
	protected function _transformProperties($css){
		$css = preg_replace('/(\\s|{)([a-zA-Z-]+)\\s?:\\s?([^;}{]*);/', '$1<property type="$2">$3</property>', $css);
		return $css;
	}
	
	protected function _transformSelectors($css){
		preg_match_all('/([a-zA-Z.#*][a-zA-Z0-9,\\s:.#_-]*)\\s?{/', $css, $results,  PREG_SET_ORDER |  PREG_OFFSET_CAPTURE  );
		$posMod = 0; //String Position Modifer.
		foreach($results as $result){
			//var_dump($result);
			//var_dump(substr($css, 0, $result[0][1]));
			$offset = $result[0][1];
			$pStart = $offset + $posMod;
			$pEnd = $pStart + strlen($result[0][0]);
			
			$cssBefore = substr($css, 0, $pStart);
			$cssAfter = substr($css, $pEnd  );
			
			$cssNew = '<ruleset>' . $this->_parseSelectors($result[1][0]);
			
			$posMod += strlen($cssNew) - strlen($result[0][0]);
			
			$css = $cssBefore . $cssNew .  $cssAfter;
		}
		$css = str_replace('}','</ruleset>', $css);
		return $css;
	}
	
}